/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package seminario.dao;

import java.io.Serializable;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;
import javax.persistence.TypedQuery;

/**
 *
 * @author bpmlab
 * @param <T>
 */
public class GenericDAO<T> implements Serializable {
    
    private final EntityManager em = FabricaDAO.getFactory().createEntityManager();
    
    public boolean criar(T o) {
        EntityTransaction tx = null;
        try {
          tx = em.getTransaction();
          tx.begin();
          em.persist(o);
          tx.commit();
          return true;
        } catch (Exception e) {
            if (tx != null && tx.isActive()) {
                tx.rollback();
            }
            return false;
        }
    }
    
    public boolean alterar(T o) {
        EntityTransaction tx = null;
        try {
          tx = em.getTransaction();
          tx.begin();
          em.merge(o);
          tx.commit();
          return true;
        } catch (Exception e) {
            if (tx != null && tx.isActive()) {
                tx.rollback();
            }
            return false;
        }
    }
    
    public boolean remover(T o) {
        EntityTransaction tx = null;
        try {
          tx = em.getTransaction();
          tx.begin();
          em.remove(em.merge(o));
          tx.commit();
          return true;
        } catch (Exception e) {
            if (tx != null && tx.isActive()) {
                tx.rollback();
            }
            return false;
        }
    }
    
    public T obterPorId(Class<T> clazz, Integer id) {
        TypedQuery<T> query = em.createNamedQuery(clazz.getSimpleName() + ".findById", clazz)
                .setParameter("id", id);
        return query.getSingleResult();
    }
    
    public List<T> obterTodos(Class<T> clazz) {
        TypedQuery<T> query = em.createNamedQuery(clazz.getSimpleName() + ".findAll", clazz);
        return query.getResultList();
    }

    public EntityManager getEntityManager() {
        return em;
    }
    
}
